package cn.momoshenchi.product.service.impl;

import cn.momoshenchi.common.constant.ProdcutConstant;
import cn.momoshenchi.product.dao.AttrGroupDao;
import cn.momoshenchi.product.dao.CategoryDao;
import cn.momoshenchi.product.entity.AttrAttrgroupRelationEntity;
import cn.momoshenchi.product.entity.AttrGroupEntity;
import cn.momoshenchi.product.entity.CategoryEntity;
import cn.momoshenchi.product.service.AttrAttrgroupRelationService;
import cn.momoshenchi.product.service.AttrGroupService;
import cn.momoshenchi.product.service.CategoryService;
import cn.momoshenchi.product.vo.AttrGroupRelationVo;
import cn.momoshenchi.product.vo.AttrReVo;
import cn.momoshenchi.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.momoshenchi.common.utils.PageUtils;
import cn.momoshenchi.common.utils.Query;

import cn.momoshenchi.product.dao.AttrDao;
import cn.momoshenchi.product.entity.AttrEntity;
import cn.momoshenchi.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService
{

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params)
    {
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params));

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr)
    {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        save(attrEntity);

        if(attr.getAttrType()== ProdcutConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
        &&attr.getAttrGroupId()!=null)
        {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long categoryId, String attrType)
    {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(attrType) ?
                        ProdcutConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                        ProdcutConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (categoryId != 0)
        {
            queryWrapper.eq("category_id", categoryId);

        }
        String key = (String) params.get("key");
        if (!StringUtils.isBlank(key))
        {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);


        List<AttrEntity> records = page.getRecords();
        List<AttrReVo> list = records.stream().map(attr -> {
            AttrReVo vo = new AttrReVo();
            BeanUtils.copyProperties(attr, vo);

            if ("base".equalsIgnoreCase(attrType))
            {
                AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService.getOne(
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attr.getAttrId()));
                if (attrAttrgroupRelationEntity != null &&attrAttrgroupRelationEntity.getAttrGroupId()!=null)
                {
                     long attrgroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
                    vo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }


            CategoryEntity categoryEntity = categoryDao.selectById(attr.getCategory_id());
            if (categoryEntity != null)
            {
                vo.setCategoryName(categoryEntity.getName());
            }
            return vo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }

    /*
      和上面一样
        还要设置groupname,categoryname

     */
    @Override
    public AttrReVo getAttrInfo(Long attrId)
    {
        AttrReVo attrReVo = new AttrReVo();
        AttrEntity attrEntity = getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrReVo);

        if(attrEntity.getAttrType()==ProdcutConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationService
                    .getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrId));
            if (attrAttrgroupRelationEntity != null)
            {
                long attrgroupId = attrAttrgroupRelationEntity.getAttrGroupId();
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
                if (attrGroupEntity != null)
                {
                    attrReVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    attrReVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
                }
            }
        }

        Long categoryId = attrEntity.getCategory_id();
        Long[] path = categoryService.findCategoryPath(categoryId);
        attrReVo.setCategoryPath(path);
        CategoryEntity categoryEntity = categoryService.getById(categoryId);
        if (categoryEntity != null)
        {
            attrReVo.setCategoryName(categoryEntity.getName());
        }

        return attrReVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrReVo attr)
    {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        updateById(attrEntity);
        if(attrEntity.getAttrType()==ProdcutConstant.AttrEnum.ATTR_TYPE_BASE.getCode())
        {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attr.getAttrId());
            int count = attrAttrgroupRelationService.count(new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attr.getAttrId()));
            if (count > 0)
            {
                attrAttrgroupRelationService.update(attrAttrgroupRelationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attr.getAttrId()));
            }
            else
            {
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            }
        }


    }

    /**
     * 根据分组Id查询所有的属性id
     * 然后查询所有的属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId)
    {
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        List<Long> collect = list.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if(collect.size()>0)
        {
            List<AttrEntity> attrEntities = listByIds(collect);
            return attrEntities;
        }
       return  new LinkedList<>();
    }

    @Override
    public void removeRelation(AttrGroupRelationVo[] vo)
    {

        List<AttrAttrgroupRelationEntity> collect = Arrays.stream(vo).map((attr) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attr, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationService.deleteBatchRelation(collect);
    }

    /**
     *
     * 获取没有关联的属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId)
    {
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        Long id = attrGroupEntity.getCategoryId();


        List<AttrGroupEntity> groupEntities = attrGroupService.list(new QueryWrapper<AttrGroupEntity>()
                .eq("category_id", id));
        List<Long> collect = groupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());

        List<AttrAttrgroupRelationEntity> attr_group_id = attrAttrgroupRelationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .in("attr_group_id", collect));

        List<Long> attrids = attr_group_id.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());

        //移除不可选属性,获得
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("category_id", id).eq("attr_type",ProdcutConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if(attrids.size()>0)
        {
        queryWrapper.notIn("attr_id", attrids);
        }
        String key= (String) params.get("key");
        if(!StringUtils.isBlank(key))
        {
            queryWrapper.and(wrapper -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });

        }
        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils( page);
    }

    /**
     * 查询
     *
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds)
    {
        return baseMapper.selectSearchAttrs(attrIds);

    }

}